package com.huanghuai.retail.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huanghuai.retail.entity.SInventory;
import com.huanghuai.retail.entity.SWarnInfo;
import com.huanghuai.retail.mapper.SWarnInfoMapper;
import com.huanghuai.retail.service.ISWarnInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhangshuo
 * @since 2023-05-07
 */
@Service
@Slf4j
public class SWarnInfoServiceImpl extends ServiceImpl<SWarnInfoMapper, SWarnInfo> implements ISWarnInfoService {

//    当库存产生变化达到条件预警   返回空字符串是 成功  返回有数据的是 失败

    @Override
    public String addWhenNeed(SInventory sInventory) {
        SWarnInfo sWarnInfo = new SWarnInfo();
        if (sInventory.getProductId() == null || sInventory.getStorageId() == null || sInventory.getId() == null) {
            log.error("传入数据不足");
            return "传入数据不足";
        }
        sWarnInfo.setStorageId(sInventory.getStorageId());
        sWarnInfo.setProductId(sInventory.getProductId());
        int i = sInventory.getNumber() / sInventory.getLastNumber() * 100;
        LambdaQueryWrapper<SWarnInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SWarnInfo::getProductId, sWarnInfo.getProductId());
        queryWrapper.eq(SWarnInfo::getStorageId, sWarnInfo.getStorageId());
        queryWrapper.eq(SWarnInfo::getIsHandle, "0");
        SWarnInfo one = this.getOne(queryWrapper);
        if (i <= sInventory.getMinRate() || sInventory.getNumber() <= 0 || sInventory.getLastNumber() <= 0) {
            if (one == null){
                sWarnInfo.setMessage("库存不足");
                sWarnInfo.setDate(LocalDateTime.now());
                boolean save = this.save(sWarnInfo);
                if (!save) {
                    log.error("插入警告信息失败");
                    return "插入警告信息失败";
                }
            }

        }

        if (i >=100) {


            if (one !=null && "0".equals(one.getIsHandle())) {
                one.setIsHandle("1");
                boolean b = this.updateById(one);
                if (!b) {
                    log.error("更改已解决失败");
                    return "更改已解决失败";
                }
            }

        }


        return "";

    }


}
